package dyl.sys.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import dyl.common.util.Constants;
import dyl.common.util.CryptTool;
import dyl.sys.bean.SysUser;
import dyl.sys.service.UserService;
@Controller
public class LoginAction extends BaseAction {
	@Resource
	UserService userService;
	@RequestMapping(value = "/login!intologin.do")
	public String intologin(HttpServletRequest request){
		if(getSysUser(request)!=null)return "redirect:/index.do";
		return "/login";
	}
	@RequestMapping(value = "/login.do")
	public String login(String username,String password,HttpSession session,HttpServletRequest request){
		SysUser user = userService.findByUsername(username);
		if (user == null||!user.getPassword().equals(CryptTool.md5(password))){
			request.setAttribute("username", username);
			request.setAttribute("loginMsg", "用户名或密码不正确");
			return "/login";
		}
		userService.setRoleInUser(user);
		session.setAttribute(Constants.SESSION_USER_KEY, user);
		String backToUrl = request.getParameter("backToUrl");
		if(StringUtils.isNotEmpty(backToUrl)){
			return "redirect:"+backToUrl;
		}
		return "redirect:/index.do";
	}
	@RequestMapping(value = "/logout.do")
	public String logout(HttpSession session){
		session.invalidate();
		return "/login";
	}
	@ResponseBody
	@RequestMapping(value = "/modifyPwd.do")
	public String modifyPwd(String password,String oldPassword,HttpServletRequest request){
		return userService.userService(password,oldPassword, getSysUser(request));
	}
}
